package class05;

/**
 * @Auther: xw
 * @Create: 2022/3/18 10:16
 * @Description: 不用加减乘除符号实现加减乘除
 */
public class BitAddMinusMultiDiv {
    /**
     * 加
     * @param a
     * @param b
     * @return
     */
    public static int add(int a,int b){
        int sum = 0;
        while(b != 0){
            sum = a ^ b;//无进位相加
            b = (a & b) << 1; //进位信息 b'
            a = sum; // a'
        }
        return sum;
    }

    /**
     * 取n的相反数
     * @param n
     * @return
     */
    public static int negNum(int n) {
        return add(~n, 1);
    }

    /**
     * 减法   a + (-b)
     * @param a
     * @param b
     * @return
     */
    public static int minus(int a,int b){
        return (add(a,negNum(b)));
    }

    /**
     * 乘法
     * @param a
     * @param b
     * @return
     */
    public static int multiply(int a,int b){
        int res = 0;
        while(0 != b){
            if ((b&1) != 0){
                res = add(res,a);
            }
            a <<= 1;
            b >>>= 1;
        }
        return res;
    }
    public static boolean isNeg(int n) {
        return n < 0;
    }

    public static int div(int a, int b) {
        int x = isNeg(a) ? negNum(a) : a;
        int y = isNeg(b) ? negNum(b) : b;
        int res = 0;
        for (int i = 30; i >= 0; i = minus(i, 1)) {
            if ((x >> i) >= y) {
                res |= (1 << i);
                x = minus(x, y << i);
            }
        }
        return isNeg(a) ^ isNeg(b) ? negNum(res) : res;
    }

    public static int divide(int a, int b) {
        if (a == Integer.MIN_VALUE && b == Integer.MIN_VALUE) {
            return 1;
        } else if (b == Integer.MIN_VALUE) {
            return 0;
        } else if (a == Integer.MIN_VALUE) {
            if (b == negNum(1)) {
                return Integer.MAX_VALUE;
            } else {
                int c = div(add(a, 1), b);
                return add(c, div(minus(a, multiply(c, b)), b));
            }
        } else {
            return div(a, b);
        }
    }


    public static void main(String[] args) {


    }
}
